package com.xinjie.www.service.comment;

import com.xinjie.www.dao.BaseDao;
import com.xinjie.www.dao.comment.CommentDao;
import com.xinjie.www.dao.comment.CommentDaoImpl;
import com.xinjie.www.po.Comment;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentServiceImpl implements CommentService {
    private final CommentDao commentDao;

    public CommentServiceImpl() {
        commentDao = new CommentDaoImpl();
    }

    @Override
    public List<Comment> getComment(int post) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Comment> comments = new ArrayList<>();
        conn = BaseDao.getConnection();
        if (conn != null) {
            comments = commentDao.getComment(conn, post);
        }
        BaseDao.closeResource(conn, null, null);
        return comments;
    }

    @Override
    public List<Comment> getManagerComment(String tieba) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Comment> comments = new ArrayList<>();
        conn = BaseDao.getConnection();
        if (conn != null) {
            comments = commentDao.getManagerComment(conn, tieba);
        }
        BaseDao.closeResource(conn, null, null);
        return comments;
    }

    @Override
    public boolean writeComment(int postId, int userId, String content, String time) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        conn = BaseDao.getConnection();
        boolean flag = false;
        if (conn != null && content != null) {
            int i = commentDao.writeComment(conn, postId, userId, content, time);
            if (i > 0) {
                flag = true;
            }
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }

    @Override
    public List<Comment> getOwnComment(int userId) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Comment> comments = new ArrayList<>();
        conn = BaseDao.getConnection();
        if (conn != null) {
            comments = commentDao.getOwnComment(conn, userId);
            BaseDao.closeResource(conn, null, null);
        }
        return comments;
    }

    @Override
    public boolean deleteOwnComment(int commentId, int postId) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        boolean flag = false;
        conn = BaseDao.getConnection();
        if (conn != null) {
            int i = commentDao.deleteOwnComment(conn, commentId, postId);
            if (i > 0) {
                flag = true;
            }
            BaseDao.closeResource(conn, null, null);
        }
        return flag;
    }
}
